#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cassert>
#include <functional>
#include <pthread.h>
using namespace std;

namespace ThreadNS
{
    typedef std::function<void*(void*)> func_t;
    const int num = 1024;

    class Thread
    {
    public:
        Thread()
        {
            char namebuffer[num];
            snprintf(namebuffer,sizeof namebuffer,"thread-%d",_threadnum++);
            _name = namebuffer;

        }
        void start(func_t func,void* args = nullptr)
        {
            _func = func;
            _args = args;
            int n = pthread_create(&_tid,nullptr,start_routine,this);
            assert(n == 0);//assert在debug下是存在的，release下是不存在的 
            (void)n;//那么n就是一个定义未被使用的变量，在有些编译器下会报warning
        }
        void join()
        {
            int n = pthread_join(_tid,nullptr);
            assert(n == 0);
            (void)n;
        }
        string threadname()
        {
            return _name;
        }
        ~Thread()
        {}
    private:
         //在类内创建线程，想让线程执行对应的方法，需要将方法设置为static
        static void* start_routine(void* args)  //类内成员，有缺省参数
        {
            Thread* _this = static_cast<Thread*>(args);
            return _this->callback();
        }
        void* callback()
        {
            return _func(_args);
        }
    private:
        string _name;
        pthread_t _tid;
        func_t _func;
        void* _args;
        static int _threadnum;
    };
    int Thread:: _threadnum = 1;
}   // end namespace ThreadNS
